package com.sunye.mongodb;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sunye.elasticsearch.entity.EsDog;
import com.sunye.elasticsearch.entity.EsDogSearchDTO;
import com.sunye.elasticsearch.service.EsDogSellingPointService;
import com.sunye.elasticsearch.service.EsDogService;
import com.sunye.mongodb.service.MongoDogIndexService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
import org.springframework.data.mongodb.core.index.GeospatialIndex;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author sunye
 * @date 2023/5/17--13:55
 */
@RestController
@RequestMapping("MongoDBController")
@Slf4j
public class MongoDBController {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private EsDogService esDogService;

    @Autowired
    private EsDogSellingPointService esDogSellingPointService;

    @Autowired
    private MongoDogIndexService mongoDogIndexService;



    /**
     * 初始化索引
     */
    @RequestMapping("/init")
    public void init(){
        //查询数据
        QueryWrapper<EsDog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted","0");
        List<EsDog> list = esDogService.list(queryWrapper);
        //封装数据
        List<MongoDogIndex> mongoDogIndexList = new ArrayList<>();
        for (EsDog esDog : list) {
            MongoDogIndex mongoDogIndex = new MongoDogIndex();
            BeanUtils.copyProperties(esDog,mongoDogIndex);
            String[] sellingPoint = esDog.getSellingPointId().split(",");
            List<String> sellingPointIds = Arrays.asList(sellingPoint);
            //存储卖点
            List<MongoDogSellingPointIndex> esDogSellingPointList =  esDogSellingPointService.getMongoSellingPoint(sellingPointIds);
            mongoDogIndex.setSellingPointList(esDogSellingPointList);
            //存储经纬度
            mongoDogIndex.setLocation(new Double[]{esDog.getLon(),esDog.getLat()});

            //存储sku
            List<MongoDogIndex.Sku> skuList = new ArrayList<>();
            MongoDogIndex.Sku sku = new MongoDogIndex.Sku();
            sku.setId(esDog.getId()+"");
            sku.setTitle(esDog.getDogBreed());
            skuList.add(sku);
            mongoDogIndex.setSkuList(skuList);
            mongoDogIndexList.add(mongoDogIndex);
        }
        //将输入存入到mongodb里
        if (!mongoDogIndexList.isEmpty()) {
//            //批量删除数据
//            Query query = new Query();
//            List<MongoDogIndex> prs = mongoTemplate.find(query, MongoDogIndex.class);
//            mongoTemplate.remove(Query.query(Criteria.where("id").in(CollUtil.getFieldValues(prs,"id"))),MongoDogIndex.class);
            //删除集合
            mongoTemplate.dropCollection(MongoDogIndex.class);
            //批量新增(自动生成集合)
            mongoTemplate.insert(mongoDogIndexList,MongoDogIndex.class);
            //新增地理空间索引
            mongoTemplate.indexOps(MongoDogIndex.class).ensureIndex( new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE) );
            mongoTemplate.indexOps(MongoDogIndex.class).ensureIndex( new GeospatialIndex("location"));

        }

    }



    //http://localhost:8088/MongoDBController/searchDogsByMongoDB/1/10?keyword=春寒料峭&color=白&recommend=1&price=200_1000
    //http://localhost:8088/MongoDBController/searchDogsByMongoDB/1/10?sellingPointIds=1,2  (嵌套查询and)
    //http://localhost:8088/MongoDBController/searchDogsByMongoDB/1/10?skuIds=1,2  (嵌套查询or)
    //http://localhost:8088/MongoDBController/searchDogsByMongoDB/1/10?position=40.258397_110.742781&sort=price_desc (经纬度排序)
    @GetMapping("/searchDogsByMongoDB/{start}/{size}")
    public SearchResponse searchDogsByMongoDB(EsDogSearchDTO dogSearchDTO, @PathVariable Integer start, @PathVariable Integer size) {
        if (start == null || start.equals(0)) {
            start = 1;
        }
        if (size == null || size.equals(0)) {
            size = 10;
        }

        SearchResponse res = mongoDogIndexService.searchDogsByMongoDB(dogSearchDTO,start,size);
        return res;
    }


    //http://localhost:8088/MongoDBController/searchMongDbGroupBy?groupByAge=1&groupByAgeAndBreed=1&groupByMaxAge=1
    @GetMapping("/searchMongDbGroupBy")
    public List searchMongDbGroupBy(EsDogSearchDTO dogSearchDTO) {
        List list = mongoDogIndexService.searchMongDbGroupBy(dogSearchDTO);
        return list;
    }



//    //创建集合
//    @RequestMapping(value = "/createCollection")
//    @ResponseBody
//    public String createCollection() {
//        boolean emp = mongoTemplate.collectionExists("website");
//        if(emp){
//            mongoTemplate.dropCollection("website");
//        }
//        mongoTemplate.createCollection("website");
//        return "success";
//    }
//
//
    //创建一个索引(自动创建集合)
    @RequestMapping(value = "/setMongoRepository")
    @ResponseBody
    public String setMongoRepository() {
        Person person = new Person();
        person.setName("李四");
        person.setAge(18);
        mongoTemplate.save(person);
        return "success";
    }

}
